<?php

namespace App\Http\Controllers;

use App\Comment;
use App\Http\Requests\PostRequest;
use App\Post;
use App\Zan;
use Illuminate\Http\Request;


class PostController extends Controller
{
    //文章列表页
    public function index(){
        //$posts = Post::orderBy("created_at","desc")->paginate(6);
        //
//        $posts = Post::with('user:id,name')->withCount('comments','zans')->orderByDesc("created_at")->paginate(6);
        /*select `posts`.*, (
            select count(*) from `comments` where `posts`.`id` = `comments`.`post_id`) as `comments_count`,
            (select count(*) from `zans` where `posts`.`id` = `zans`.`posd_id`) as `zans_count`
        from `posts` order by `created_at` desc limit 6 offset 0*/
        $posts = Post::with('user:id,name')->withCount(['comments','zans'])->orderByDesc("created_at")->paginate(6);
//        return view('post/index',compact('posts'));

        //dd($posts[0]->user->id);
        return view('post/index',compact('posts'));
//        return $posts1;
        //return view('post.index');
    }



    //创建文章页面

    public function create()
    {
        return view('post/create');
    }
    //创建逻辑
    public function store(Request $request){


        //表单验证
        $a = $this->validate($request,[
        //$a = $this->validate($request->all(),[
            'title' => 'required|max:255|min:4',
            'content' => 'required|min:10',
        ]);
        $b = $validatedData = $request->validate([
            'title' => 'required|max:255|min:4',
            'content' => 'required|min:10',
        ]);

        //传递数组
//        dd(request(['title','content']));
//        dd($request->input());
//        dd($request->all());
//        dd($request->only(['title', 'content']));
//        $post1 = Post::create(request(['title','content']));
//        $post2 = Post::create($request->input(['title','content']));
        //逻辑
        $user_id = \Auth::id();
        $params = array_merge(request(['title','content']),compact('user_id'));
        //dd($params);
        $post = Post::create($params);

    }
    public function store1(PostRequest $request){

        /*Laravel 会自动调用 UserAddressRequest 中的 rules()
        方法获取校验规则来对用户提交的数据进行校验，因此这里我们不需要手动调用 $this->validate() 方法。

         表单请求验证（FormRequest）的工作机制，是利用 Laravel 提供的依赖注入功能，
         在控制器方法，如我们的 update() create() 方法声明中，传参 UserRequest。
        这将触发表单请求类的自动验证机制，验证发生在 PostRequest 中，并使用此文件中方法 rules() 定制的规则，
         只有当验证通过时，才会执行 控制器 update() 方法中的代码。否则抛出异常，
         并重定向至上一个页面，附带验证失败的信息。*/
        //逻辑
        $user_id = 1;
        //$params = array_merge(request(['title','content']),compact('user_id'));
        $params = array_merge($request->only(['title', 'content']),compact('user_id'));
        //dd($params);
        $post = Post::create($params);
        //页面渲染
        return redirect('/posts');

    }
    //上传图片
    public function imageUpload(Request $request){

        //dd(request()->all());

        $path = $request->file('wangEditorH5File')->storePublicly(md5(time()));
        //dd($path);
        return asset('storage/'. $path);
    }
    //详情页面
    public function show(Post $post){

        //模型加载完成后在进行渴求式加载
        $post->load('comments','comments.user');
        return view('post.show',compact('post'));
    }

    //编辑页面
    public function edit(Post $post){

        return view('post/edit',compact('post'));
    }
    //编辑更新逻辑
    public function update(Post $post,PostRequest $postRequest){

        //$post->update($postRequest->all());
        //dd($postRequest->all());
        //dd($postRequest->only(['title', 'content']));

        //权限验证
        $this->authorize('update',$post);

        //逻辑
        $post->title = request('title');
        $post->content = request('content');
        $post->save();
        return redirect()->route('posts.show', $post->id)->with('success', '更新成功！');
        //return redirect("/posts/{$post->id}");
    }

    //删除文章
    public function delete(Post $post)
    {
//        dd($post);
        //TODO:用户的权限验证

        //权限验证
        $this->authorize('delete',$post);
        $post->delete();
        return redirect("/posts");
    }

    //给文章添加评论
    public function comment(Post $post){

        $this->validate(request(),[
           'content' => "required|min:3"
        ]);
        //增加评论逻辑
//        $comment = new Comment();
//        $comment->user_id = \Auth::id();
//        $comment->content = request('content');

        $comment = new Comment([
           'user_id' => \Auth::id(),
            'content' => request('content')
        ]);
        //更新「从属」关联
//        $post->comments()->save($comment);
        $post->comments()->create([
            'user_id' => \Auth::id(),
            'content' => request('content')
        ]);
        //渲染
        return back();

    }

    //赞
    public function zan(Post $post){

        $param = [
            'user_id' => \Auth::id(),
            'posd_id' => $post->id
        ];
        //有则查找 没则创建  保证不会重复创建数据
        /*firstOrCreate 方法将会使用指定的字段／值对，
        来尝试寻找数据库中的记录。如果在数据库中找不到模型，则会使用指定的属性来添加一条记录。*/
//        Zan::firstOrCreate($param);
        $post->zans()->firstOrCreate($param);
        return back();
    }
    //取消赞
    public function unzan(Post $post){

        $post->zan(\Auth::id())->delete();
        return back();
    }
}

